package com.example.jetpackpaging.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import com.example.jetpackpaging.adapter.RepoAdapter
import com.example.jetpackpaging.adapter.RepoLoadMoreAdapter
import com.example.jetpackpaging.databinding.ActivityMainBinding
import com.example.jetpackpaging.viewmodel.RepoViewModel
import kotlinx.coroutines.flow.collectLatest

class MainActivity : AppCompatActivity() {

   private val repoViewModel by viewModels<RepoViewModel>()

   private val mBinding : ActivityMainBinding by lazy {
       ActivityMainBinding.inflate(layoutInflater)
   }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(mBinding.root)
        val repoAdapter = RepoAdapter(this)
        mBinding.apply {
           recyclerView.adapter = repoAdapter.withLoadStateFooter(RepoLoadMoreAdapter(this@MainActivity))
           swipeRefreshLayout.setOnRefreshListener {
               repoAdapter.refresh()
           }
        }

        lifecycleScope.launchWhenCreated {
            repoViewModel.loadRepoData().collectLatest {
                repoAdapter.submitData(it)
            }
        }
        //下拉刷新
        lifecycleScope.launchWhenCreated {
            repoAdapter.loadStateFlow.collectLatest { state ->
                mBinding.swipeRefreshLayout.isRefreshing = state.refresh is LoadState.Loading
            }
        }
    }

}